﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mBook.Entity;
using JJY.CommonHelper;
using HtmlAgilityPack;
using mBook.Business;
using System.Text;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class DangDangWeekTop : System.Web.UI.Page
{
    private readonly string EmptyString = string.Empty;


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtUrl.Text = "http://bang.dangdang.com/book/bestSeller/" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&page=2" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&page=3" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&page=4" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&page=5";

            txtUrl2.Text = "http://bang.dangdang.com/book/bestSeller/?&page=1&catpath=01.03.00.00.00.00&catname=%D0%A1%CB%B5&show=T" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&catpath=01.03.00.00.00.00&catname=%D0%A1%CB%B5&show=T&page=2" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&catpath=01.03.00.00.00.00&catname=%D0%A1%CB%B5&show=T&page=3" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&catpath=01.03.00.00.00.00&catname=%D0%A1%CB%B5&show=T&page=4" + Environment.NewLine +
                            "http://bang.dangdang.com/book/bestSeller/?&catpath=01.03.00.00.00.00&catname=%D0%A1%CB%B5&show=T&page=5";

        }
    }

    protected void btnFetch_OnClick(object sender, EventArgs e)
    {
        try
        {
            string[] urlSet = txtUrl.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            FetchData(urlSet);            
        }
        catch(Exception ex)
        {
            lblInfo.Text = ex.ToString(); 
        }
    }

    protected void btnFetch2_OnClick(object sender, EventArgs e)
    {
        try
        {
            string[] urlSet = txtUrl2.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            FetchData(urlSet);
        }
        catch (Exception ex)
        {
            lblInfo.Text = ex.ToString();
        }
    }

    protected void FetchData(string[] urlSet)
    {
        IList<ddWeekTop> weekTopSet = new List<ddWeekTop>();

        foreach (string url in urlSet)
        {
            weekTopSet = weekTopSet.Concat(GetData(url)).ToList();
        }

        for (int i = 0; i < weekTopSet.Count; i++)
        {
            if (weekTopSet[i] != null)
            {
                weekTopSet[i].ThisWeekRanking = i + 1;
            }
        }

        HtmlTable htmlTable = CreateTable(weekTopSet);
        ExportTable(htmlTable);

        //new DDWeekTopBS().DDWeekTopInsert(weekTopSet);

        lblInfo.Text = "Fetch Successful!";
    }

    protected void btnClear_OnClick(object sender, EventArgs e)
    {
        try
        {
            if (new DDWeekTopBS().DDWeekTopRemove())
            {
                lblInfo.Text = "Clear Successful!";
            }
        }
        catch (Exception ex)
        {
            lblInfo.Text = ex.ToString();
        }
    }

    private IList<ddWeekTop> GetData(string url)
    {
        IList<ddWeekTop> result = new List<ddWeekTop>();

        string str = HttpRequestService.GetHtmlSourceByUrl(url)
                .Replace(@"\t", EmptyString).Replace(@"\r", EmptyString).Replace(@"\n", EmptyString)
                .Replace("&nbsp;", EmptyString).Replace("　", EmptyString).Trim();
        
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(str);


        HtmlNodeCollection nodeBookSet = doc.DocumentNode.SelectNodes("//div[@name='__BangList']/div");


        string bookName = string.Empty;
        string author = string.Empty;
        string press = string.Empty;
        DateTime pressDate = new DateTime(1900, 1, 1);

        foreach (HtmlNode nodeDiv in nodeBookSet)
        {
            if (nodeDiv != null)
            {
                HtmlNodeCollection nodeLiSet = doc.DocumentNode.SelectNodes(nodeDiv.XPath + "/div[@class='book_info']/ul/li");
                foreach (HtmlNode nodeLi in nodeLiSet)
                {
                    switch (nodeLi.Attributes["class"].Value)
                    {
                        case "bookname blue":
                            bookName = doc.DocumentNode.SelectNodes(nodeLi.XPath + "/a")[0].Attributes["title"].Value;
                            break;
                        case "author":
                            if (nodeLi.InnerText.IndexOf('：') > -1)
                            {
                                author = nodeLi.InnerText.Split('：')[1].Replace(" ", EmptyString).Replace("著", EmptyString);
                            }
                            break;
                        case "press":
                            if (nodeLi.InnerText.IndexOf('：') > -1)
                            {
                                press = nodeLi.InnerText.Split('：')[1].Replace(" ", EmptyString);
                            }
                            break;
                        case "press_date":
                            if (nodeLi.InnerText.IndexOf('：') > -1 && 
                                nodeLi.InnerText.Split('：')[1].Trim() != string.Empty)
                            {
                                DateTime.TryParse(nodeLi.InnerText.Split('：')[1], out pressDate);
                            }
                            break;
                    }
                }

                result.Add(new ddWeekTop()
                {
                    WeekTopID = Guid.NewGuid(),
                    BookName = bookName,
                    Author = author,
                    Press = press,
                    PressDate = pressDate,
                    CreateDate = DateTime.Now,
                    ModifyDate = DateTime.Now,
                    IsDeleted = false
                });
            }
        }

        return result;
    }


    private HtmlTable CreateTable(IList<ddWeekTop> amazonTopSet)
    {
        HtmlTable result = new HtmlTable();
        
        HtmlTableRow rowTitle = new HtmlTableRow();
        rowTitle.Cells.Add(new HtmlTableCell() { InnerText = "排名" });
        rowTitle.Cells.Add(new HtmlTableCell() { InnerText = "书名" });
        rowTitle.Cells.Add(new HtmlTableCell() { InnerText = "作者" });
        rowTitle.Cells.Add(new HtmlTableCell() { InnerText = "出版社" });
        rowTitle.Cells.Add(new HtmlTableCell() { InnerText = "出版时间" });
        result.Rows.Add(rowTitle);

        foreach (ddWeekTop amazonTop in amazonTopSet)
        {
            HtmlTableRow row = new HtmlTableRow();
            row.Cells.Add(new HtmlTableCell(){ InnerText = amazonTop.ThisWeekRanking.ToString()});
            row.Cells.Add(new HtmlTableCell(){ InnerText = amazonTop.BookName});
            row.Cells.Add(new HtmlTableCell(){ InnerText = amazonTop.Author});
            row.Cells.Add(new HtmlTableCell(){ InnerText = amazonTop.Press});
            row.Cells.Add(new HtmlTableCell(){ InnerText = amazonTop.PressDate.ToString("yyyy-MM-dd")});
            result.Rows.Add(row);
        }
        return result;
    }

    private void ExportTable(HtmlTable table)
    {
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(System.DateTime.Now.ToString("yyyy-MM-dd") + ".xls", System.Text.Encoding.UTF8));
        HttpContext.Current.Response.ContentType = "application/ms-xls";
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;


        //Init HtmlWriter
        StringWriter writer = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);

        table.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write(writer.ToString());
        HttpContext.Current.Response.End();
    }

}